//
//  ViewController.m
//  sqlite
//
//  Created by hoho on 14-11-9.
//  Copyright (c) 2014年 hoho. All rights reserved.
//

#import "ContactController.h"
#import "DBManager.h"
#import "Contact.h"

@interface ContactController ()

@end

@implementation ContactController {
    NSArray *arrPeopleInfo;
    NSInteger peopleInfoId;
    Contact * contact;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    contact = [[Contact alloc]init];
    [self loadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadData{
    arrPeopleInfo = [contact findAll];
    [_tv reloadData];
}

- (void)editWasFinished {
    [self loadData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44.0;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return arrPeopleInfo.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ContactCell"];
    
    UILabel *contactNameLable = (UILabel *)[cell viewWithTag:1];
    UILabel *phoneNumberLable = (UILabel *) [cell viewWithTag:2];
    contactNameLable.text = [[arrPeopleInfo objectAtIndex:indexPath.row]objectForKey:@"contact_name"];
    phoneNumberLable.text = [[arrPeopleInfo objectAtIndex:indexPath.row]objectForKey:@"phone_number"];
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    peopleInfoId = [[[arrPeopleInfo objectAtIndex:indexPath.row]objectForKey:@"id"] intValue];
    [self performSegueWithIdentifier:@"GotoEdit" sender:self];
    
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    ContactEditController *editController = [segue destinationViewController];
    editController.delegate = self;
    editController.peopleInfoId = peopleInfoId;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        peopleInfoId = [[[arrPeopleInfo objectAtIndex:indexPath.row]objectForKey:@"id"] intValue];
        NSInteger result = [contact del:peopleInfoId];
        if(result > 0) {
            [self loadData];
        }
    }
}

- (IBAction)addNewContact:(id)sender {
    peopleInfoId = -1;
    [self performSegueWithIdentifier:@"GotoEdit" sender:self];
}

@end
